<html>
  <head>
    <title>A save and restore canvas state example</title>
    <meta name="DC.creator" content="Kamiel Martinet, http://www.martinet.nl/">
    <meta name="DC.publisher" content="Mozilla Developer Center, http://developer.mozilla.org">
    <script type="application/x-javascript">
      function draw() {
        var ctx = document.getElementById('canvas').getContext('2d');

        ctx.fillRect(0,0,150,150);   //  draw a rectangle with default settings
        ctx.save();                  //  Save the default state

        ctx.fillStyle = '#09F'       // Make changes to the settings
        ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings

        ctx.save();                  // Save the current state
        ctx.fillStyle = '#FFF'       // Make changes to the settings
        ctx.globalAlpha = 0.5;    
        ctx.fillRect(30,30,90,90);   // Draw a rectangle with new settings

        ctx.restore();               // Restore previous state
        ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings

        ctx.restore();               // Restore original state
        ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings
      }
    </script>
    <style type="text/css">
      body { margin: 20px; font-family: arial,verdana,helvetica; background: #fff;}
      h1 { font-size: 140%; font-weight:normal; color: #036; border-bottom: 1px solid #ccc; }
      canvas { border: 2px solid #000; float: left; margin-right: 20px; margin-bottom: 20px; }
      pre { float:left; display:block; background: rgb(238,238,238); border: 1px dashed #666; padding: 15px 20px; margin: 0 0 10px 0; }
    </style>
  </head>
  <body onload="draw();">
    <h1>A <code>save</code> and <code>restore</code> canvas state example</h1>
    <div>
      <canvas id="canvas" width="150" height="150"></canvas>
      <pre>
function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.fillRect(0,0,150,150);   //  draw a rectangle with default settings
  ctx.save();                  //  Save the default state

  ctx.fillStyle = '#09F'       // Make changes to the settings
  ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings

  ctx.save();                  // Save the current state
  ctx.fillStyle = '#FFF'       // Make changes to the settings
  ctx.globalAlpha = 0.5;    
  ctx.fillRect(30,30,90,90);   // Draw a rectangle with new settings

  ctx.restore();               // Restore previous state
  ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings

  ctx.restore();               // Restore original state
  ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings
}
      </pre>
    </div>
  </body>
</html>
